package com.lnyt.util;

import org.springframework.util.Base64Utils;

import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Map;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class CheckUtil {
    private static String wxToken = "taozuqin18007758403";
    private static String wxAppId = "";
    private static String wxAesKey = "qAYsbZYnRwo2lcNDQh4HQ0OTy0a8m8uOD504xJiPM8o";

    // 校验微信
    public static boolean checkSignature(Map<String, String[]> prams) {
        if (prams.size() == 0)
            return false;

        String signature = prams.get("signature")[0];
        String timestamp = prams.get("timestamp")[0];
        String nonce = prams.get("nonce")[0];

        String[] arr = new String[] { wxToken, timestamp, nonce };

        try {
            Arrays.sort(arr);
        } catch (Exception exc) {
            LogUtil.log4j2().warn(exc.getMessage());
            return false;
        }

        MessageDigest sha1 = null;
        StringBuilder content = new StringBuilder();
        StringBuilder hashStr = new StringBuilder();

        for (String arrItem : arr) {
            content.append(arrItem);
        }

        try {
            sha1 = MessageDigest.getInstance("SHA-1");
            sha1.update(content.toString().getBytes());

            for (byte b : sha1.digest()) {
                hashStr.append(String.format("%02X", b));
            }
        } catch (NoSuchAlgorithmException exc) {
            LogUtil.log4j2().warn(exc.getMessage());
            return false;
        }

        return hashStr.toString().equals(signature.toUpperCase());
    }

    // 计算MD5
    public static String calcMd5(String data) {
        StringBuilder md5Str = new StringBuilder();

        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(data.getBytes());

            for (byte b : md5.digest()) {
                md5Str.append(String.format("%02X", b));
            }
        } catch (Exception exc) {
            LogUtil.log4j2().warn(exc.getMessage());
            return "00000000000000000000000000000000";
        }

        return md5Str.toString();
    }

    // URL转码
    public static String urlDecode(String data, String enc) {
        String result = null;

        try {
            result = URLDecoder.decode(data, enc);
        } catch (Exception exc) {
            exc.printStackTrace();
        }

        return result;
    }

    // Base64转码
    public static String base64Encode(String data) {
        String result = null;

        try {
            result = Base64Utils.encodeToUrlSafeString(data.getBytes());
        } catch (Exception exc) {
            exc.printStackTrace();
        }

        return result;
    }
}
